package com.xmb.wechat.view.wechat.chat;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.squareup.picasso.Picasso;
import com.xmb.wechat.R;
import com.xmb.wechat.R2;
import com.xmb.wechat.application.WechatStartApplication;
import com.xmb.wechat.base.BaseActivity;
import com.xmb.wechat.bean.PYQBean;
import com.xmb.wechat.bean.PYQTrendsBean;
import com.xmb.wechat.bean.WechatContactBean;
import com.xmb.wechat.definterface.HintListener;
import com.xmb.wechat.definterface.OnChooseMeListener;
import com.xmb.wechat.definterface.OnDeleteListener;
import com.xmb.wechat.definterface.OnPYQTrendsDelegateListener;
import com.xmb.wechat.definterface.SimpleTextWatcher;
import com.xmb.wechat.definterface.onBgChooseListener;
import com.xmb.wechat.delegate.PYQTrendsDelegate;
import com.xmb.wechat.dialog.BGSelectDailog;
import com.xmb.wechat.dialog.DelegateDeleteHintDialog;
import com.xmb.wechat.util.PicChooseUtils;
import com.xmb.wechat.util.PicLoadUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.objectbox.relation.ToMany;

/**
 * @Author lijiangop
 * @CreateTime 2020/4/14 17:11
 */
public class WechatPYQActivity extends BaseActivity {

    private static final int REQUEST_CODE_PYQ_TRENDS_NEW_ADD = 105;
    private static final int REQUEST_CODE_PYQ_TRENDS_EDIT    = 106;

    @BindView(R2.id.tv_owner)
    TextView     mTvOwner;
    @BindView(R2.id.iv_owner)
    ImageView    mIvOwner;
    @BindView(R2.id.iv_cover)
    ImageView    mIvCover;
    @BindView(R2.id.switch_un_read)
    Switch       mSwitchUnRead;
    @BindView(R2.id.et_num)
    EditText     mEtNum;
    @BindView(R2.id.ll_un_read_number)
    LinearLayout mLlUnReadNumber;
    @BindView(R2.id.iv_unread_avatar)
    ImageView    mIvUnreadAvatar;
    @BindView(R2.id.ll_un_read_avatar)
    LinearLayout mLlUnReadAvatar;
    @BindView(R2.id.recyclerView)
    RecyclerView mRecyclerView;

    private PYQBean                  mPYQBean;
    private PYQTrendsDelegate        mDelegate;
    private int                      currentIndex;
    private BGSelectDailog           mBgSelectDialog;
    private DelegateDeleteHintDialog mHintDialog;

    public WechatPYQActivity() {
        super(R.layout.activity_wechat_pyq);
    }

    @Override
    protected void initView() {
        //初始化控件
        mSwitchUnRead.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                showUnreadSwitch(isChecked);
            }
        });
        mDelegate = new PYQTrendsDelegate(this, new OnPYQTrendsDelegateListener() {
            @Override
            public void onItemClick(PYQTrendsBean entity, int position) {
                currentIndex = position;
                WechatPYQAddActivity.startForResult(WechatPYQActivity.this, entity.getId(), REQUEST_CODE_PYQ_TRENDS_EDIT);
            }

            @Override
            public void onItemRemove(PYQTrendsBean e, int i) {
                if (mHintDialog == null)
                    mHintDialog = new DelegateDeleteHintDialog(WechatPYQActivity.this, "确定删除？", new OnDeleteListener() {
                        @Override
                        public void onConfirm(PYQTrendsBean entity, int position) {
                            mDelegate.removeItem(position);
                            //数据库操作
                            WechatStartApplication.getBoxStore().boxFor(PYQTrendsBean.class).remove(entity);
                            mPYQBean.getTrends().removeById(entity.getId());
                            WechatStartApplication.getBoxStore().boxFor(PYQBean.class).put(mPYQBean);
                        }
                    });
                mHintDialog.setData(e, i);
                mHintDialog.show();
            }
        });
        mEtNum.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void onTextChangedFinish(String value) {
                showUnreadContent(value);
            }
        });
        //初始化数据
        List<PYQBean> pyqBeans = WechatStartApplication.getBoxStore().boxFor(PYQBean.class).query().build().find();
        WechatContactBean owner;
        if (pyqBeans.size() > 0 && pyqBeans.get(0) != null) {//回显
            mPYQBean = pyqBeans.get(0);
            owner = WechatContactBean.getWechatContactBean(this, mPYQBean.getOwnerId(), false);
            //未读消息
            mSwitchUnRead.setChecked(mPYQBean.isShowUnreadMsg());
            mEtNum.setText(TextUtils.isEmpty(mPYQBean.getUnReadNum()) ? "" : mPYQBean.getUnReadNum());
            WechatContactBean.setupAvatarIntoImageView(WechatContactBean.getWechatContactBean(this, mPYQBean.getUnReaderId(), false), mIvUnreadAvatar, 12);
        } else {//新增
            mPYQBean = new PYQBean();
            owner = WechatContactBean.instanceNewContactMe(this, false);
            mPYQBean.setOwnerId(owner.getId());
        }
        //朋友圈主人
        mTvOwner.setText(owner.getName());
        WechatContactBean.setupAvatarIntoImageView(owner, mIvOwner, 12);
        //朋友圈背景
        if (!TextUtils.isEmpty(mPYQBean.getCover()))
            PicLoadUtils.loadSdcardPic(mPYQBean.getCover(), mIvCover);
        showTrends(mPYQBean);
        showExemption(new HintListener() {
            @Override
            public void onConfirm() {
                //do nothing
            }

            @Override
            public void onCancel() {
                WechatPYQActivity.this.finish();
            }
        });
    }

    private void showTrends(PYQBean pyqBean) {
        if (pyqBean == null)
            return;
        ToMany<PYQTrendsBean> trends = pyqBean.getTrends();
        if (trends == null || trends.size() == 0)
            return;
        mDelegate.addData(trends);
    }

    @OnClick({R2.id.re_sender, R2.id.ll_bg, R2.id.ll_un_read_avatar, R2.id.ll_add_msg, R2.id.btn_preview})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.re_sender) {
            showRoleChooseSender(this, true, false, new OnChooseMeListener() {
                @Override
                public void onMeChoose(WechatContactBean mineContactBean) {
                    showPYQOwner(mineContactBean);
                }
            });
        } else if (id == R.id.ll_bg) {
            if (mBgSelectDialog == null) {
                mBgSelectDialog = new BGSelectDailog(WechatPYQActivity.this, new onBgChooseListener() {

                    @Override
                    public void onDefaultChoose() {
                        showCover("");
                    }

                    @SuppressLint("IntentReset")
                    @Override
                    public void onUserDefinedChoose() {
                        PicChooseUtils.chooseOnePicWithCut(WechatPYQActivity.this, 5, 4, Pic -> {
                            showCover(Pic[0]);
                        });
                    }
                });
            }
            mBgSelectDialog.show();
        } else if (id == R.id.ll_un_read_avatar) {
            showRoleChooseReceiver(this, false, false, null);
        } else if (id == R.id.ll_add_msg) {
            WechatPYQAddActivity.startForResult(WechatPYQActivity.this, -1, REQUEST_CODE_PYQ_TRENDS_NEW_ADD);
        } else if (id == R.id.btn_preview) {
            doPreview();
        }
    }

    private void doPreview() {
        if (mPYQBean.isShowUnreadMsg()) {
            if (TextUtils.isEmpty(mPYQBean.getUnReadNum())) {
                ToastUtils.showShort("请填写未读消息数");
                return;
            }
            if (mPYQBean.getUnReaderId() == -2) {
                ToastUtils.showShort("请选择未读消息用户头像");
                return;
            }
        }
        WechatStartApplication.getBoxStore().boxFor(PYQBean.class).put(mPYQBean);
        WechatPYQDetailActivity.start(WechatPYQActivity.this, mPYQBean.getId());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE_OTHER_SEND || requestCode == REQUEST_CODE_CHOOSE_NEW_ADD_SEND) {//选择朋友圈主人
            if (data == null)
                return;
            WechatContactBean result = (WechatContactBean) data.getSerializableExtra("result");
            if (result == null)
                return;
            showPYQOwner(result);
        } else if (requestCode == REQUEST_CODE_CHOOSE_OTHER_RECEIVE || requestCode == REQUEST_CODE_CHOOSE_NEW_ADD_RECEIVE) {//选择未读消息用户
            if (data == null)
                return;
            WechatContactBean result = (WechatContactBean) data.getSerializableExtra("result");
            if (result == null)
                return;
            showUnreadAvatar(result);
        } else if (requestCode == REQUEST_CODE_PYQ_TRENDS_NEW_ADD) {//添加动态
            if (data == null)
                return;
            PYQTrendsBean result = (PYQTrendsBean) data.getSerializableExtra("data");
            if (result == null)
                return;
            mDelegate.additem(result);
            //数据库操作
            mPYQBean.getTrends().add(result);
            //数据库操作
            WechatStartApplication.getBoxStore().boxFor(PYQBean.class).put(mPYQBean);
        } else if (requestCode == REQUEST_CODE_PYQ_TRENDS_EDIT) {//修改动态
            if (data == null)
                return;
            PYQTrendsBean result = (PYQTrendsBean) data.getSerializableExtra("data");
            if (result == null)
                return;
            mDelegate.removeItem(currentIndex);
            mDelegate.getData().add(currentIndex, result);
            //数据库操作
            WechatStartApplication.getBoxStore().boxFor(PYQBean.class).put(mPYQBean);
        }
    }

    //-------------------------------------------------------------------------页面数据变动及显示-----------------------------------------------------------------
    private void showPYQOwner(WechatContactBean contactBean) {
        if (contactBean == null)
            return;
        mTvOwner.setText(contactBean.getName());
        WechatContactBean.setupAvatarIntoImageView(contactBean, mIvOwner, 12);
        mPYQBean.setOwnerId(contactBean.getId());
        //数据库操作
        WechatStartApplication.getBoxStore().boxFor(PYQBean.class).put(mPYQBean);
    }

    private void showCover(String cover) {
        if (TextUtils.isEmpty(cover))
            Picasso.get().load(R.mipmap.friendactivity_mycover_bg).into(mIvCover);
        else
            PicLoadUtils.loadSdcardPic(cover, mIvCover);
        mPYQBean.setCover(cover);
        //数据库操作
        WechatStartApplication.getBoxStore().boxFor(PYQBean.class).put(mPYQBean);
    }

    private void showUnreadSwitch(boolean isChecked) {
        mPYQBean.setShowUnreadMsg(isChecked);
        mLlUnReadNumber.setVisibility(isChecked ? View.VISIBLE : View.GONE);
        mLlUnReadAvatar.setVisibility(isChecked ? View.VISIBLE : View.GONE);
        WechatStartApplication.getBoxStore().boxFor(PYQBean.class).put(mPYQBean);
    }

    private void showUnreadContent(String content) {
        mPYQBean.setUnReadNum(content);
        WechatStartApplication.getBoxStore().boxFor(PYQBean.class).put(mPYQBean);
    }

    private void showUnreadAvatar(WechatContactBean contactBean) {
        if (contactBean == null)
            return;
        WechatContactBean.setupAvatarIntoImageView(contactBean, mIvUnreadAvatar, 12);
        mPYQBean.setUnReaderId(contactBean.getId());
        //数据库操作
        WechatStartApplication.getBoxStore().boxFor(PYQBean.class).put(mPYQBean);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBgSelectDialog != null) {
            mBgSelectDialog.dismiss();
            mBgSelectDialog = null;
        }
        if (mHintDialog != null) {
            mHintDialog.dismiss();
            mHintDialog = null;
        }
    }
}
